package com.epfresh.supplier.activity;

import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.widget.ShareDialog;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;

/**
 * Created by wzh on 2016/5/6.
 */
public class WebActivity extends BaseActivity {
    private WebView webview;
    private ProgressBar pb;
    private String url;
    private String title;
    private int pushType = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        if (savedInstanceState != null) {
            url = savedInstanceState.getString(Constant.KEY_WEB_URL);
            title = savedInstanceState.getString(Constant.KEY_WEB_TITLE);
            pushType = savedInstanceState.getInt("pushType");
        } else {
            url = getIntent().getStringExtra(Constant.KEY_WEB_URL);
            title = getIntent().getStringExtra(Constant.KEY_WEB_TITLE);
            pushType = getIntent().getIntExtra("pushType", 2);
        }
//        if (TextUtils.isEmpty(url)) {
//            url = "https://www.sina.cn";
//        }
        if (title.equals("e批课堂")) {
            Log.e("_share_", url.substring(url.length() - 5, url.length()));
            righticon.setImageResource(R.mipmap.share_grey);
            righticon.setOnClickListener(this);
            righticon.setVisibility(View.VISIBLE);
        }
        pushType = getIntent().getIntExtra("pushType", 2);
        if (TextUtils.isEmpty(url)) {
            finish();
        } else {
            ivBack.setVisibility(View.VISIBLE);
            toolbarTitle.setVisibility(View.VISIBLE);
            toolbarTitle.setText(title == null ? "" : title);
            pb = (ProgressBar) findViewById(R.id.pb);
            webview = (WebView) findViewById(R.id.wv);
            pb.setVisibility(View.VISIBLE);
            webViewSetting();
            if (!TextUtils.isEmpty(url)) {
                webview.loadUrl(url);
                Log.e("h5", url);
            } else {
                //错误
            }
        }

    }

    public void webViewSetting() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互

//        settings.setAppCachePath(cacheDirPath); //设置缓存的指定路径
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//https 页面里面有http形式的图片地址
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title1) {
                if (title != null && !"".equals(title1) && title.contains("e批课堂"))
                    toolbarTitle.setText(title1);
            }
        });
        webview.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//
//                return true;
//            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onLoadResource(WebView view, String url) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }
        });

        webview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (outState == null) {
            outState = new Bundle();
        }
        outState.putString(Constant.KEY_WEB_URL, url);
        outState.putString(Constant.KEY_WEB_TITLE, title);
        outState.putInt("pushType", pushType);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else if (pushType == 0) {
            Intent main = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(main);
            finish();
        } else if (pushType == 1) {
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.righticon:
                share();
                break;
        }
    }

    ShareDialog dialog;

    private void share() {
        if (dialog == null)
            dialog = new ShareDialog(this);
        String imageUrl = "http://m.epfresh.com/images/icon.png";
        String titleStr = "e批课堂开课啦！";
        String description = "学用e批生鲜，轻轻松松赚钱";
        dialog.showDialog(url, imageUrl, description, titleStr, null);
    }


}
